package com.xudow.app.ui.user;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.xudow.app.R;
import com.xudow.app.ui.BaseActivity;
import com.xudow.app.ui.task.user.ProfileEditTask;
import com.xudow.app.util.Maps;
import com.xudow.app.util.StringUtils;

import java.util.HashMap;

/**
 * 用户名编辑Activity
 *
 * @author lukecheng
 */
public class UsernameEditActivity extends BaseActivity {

    private EditText usernameEditText;

    private ProfileEditTask profileEditTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_username_edit);

        String username = getIntent().getStringExtra("username");

        usernameEditText = (EditText) findViewById(R.id.username);
        usernameEditText.setText(username);
    }

    public void onBackBtnClick(View view) {
        finish();
    }

    /**
     * 保存按钮点击事件
     *
     * @param view
     */
    public void onSave(View view) {
        String username = usernameEditText.getText().toString().trim();
        if (StringUtils.isEmpty(username)) {
            usernameEditText.setError(getString(R.string.username_required));
            return;
        }

        HashMap<String, String> params = Maps.newHashMap();
        params.put("name", username);

        showLodingDialog(getString(R.string.processing));

        profileEditTask = new ProfileEditTask(this, profileEditHandler);
        profileEditTask.execute(params);
    }

    /**
     * 更新处理Handler
     */
    private Handler profileEditHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (ProfileEditTask.SUCCESS == msg.what) {
                String successMsg = getString(R.string.update_success);
                Toast.makeText(UsernameEditActivity.this, successMsg, Toast.LENGTH_LONG).show();

                finish();
            } else if (ProfileEditTask.ERROR_WITH_MESSAGE == msg.what) {
                String errMessage = msg.getData().getString("errMessage");
                Toast.makeText(UsernameEditActivity.this, errMessage, Toast.LENGTH_LONG).show();
            } else if (ProfileEditTask.ERROR == msg.what) {
                String errMessage = getString(R.string.update_error);
                Toast.makeText(UsernameEditActivity.this, errMessage, Toast.LENGTH_LONG).show();
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode && null != profileEditTask
                && !profileEditTask.isCancelled()) {
            profileEditTask.cancel(true);
            profileEditTask = null;
        }

        return super.onKeyDown(keyCode, event);
    }

}
